
'use strict';

const BaseService = require("./base");


class CollectService extends BaseService{

    async collectListByUser(body){
        const {Op} = this.app.Sequelize
        const {user_id} = body
        const collects = this.app.model.Collect.findAll({
            where:{
                user_id,
                [Op.and]:{status:1}
            }
        })
        return collects
    }

    async changeCollectStatus(body){
        const params = this.app._.cloneDeep(body)
        const {literal} = this.app.Sequelize
        // status 1-收藏  0-取消收藏
        const {user_id, article_id,status} = params
        const curCollect = await this.app.model.Collect.findOne({
            where:{
                user_id,article_id
            }
        })
        const addOrReduce = status?'collect_count + 1':'collect_count - 1'
        if(curCollect){
            const {id} = curCollect
            await this.app.model.Collect.update({status},{
                where:{
                    id
                }
            })
            await this.app.model.Article.update({collect_count:literal(addOrReduce)},{
                where:{id:article_id}
            })
        }else{
            params.create_time = new Date()
            await this.app.model.Collect.create(params)
            await this.app.model.Article.update({collect_count:literal(addOrReduce)},{
                where:{id:article_id}
            })
        } 
    } 
}


module.exports = CollectService;